<script lang="ts" setup>
import { onMounted, ref } from 'vue';

import { handleTree } from '@vben/utils';

import { message, Tree } from 'ant-design-vue';

import {
  getDingdDeptInfoSync,
  getDingdDeptInfoSyncState,
  getDingdDeptInfoTree,
} from '#/api/moxi/dingdattendanceinfo';

const emit = defineEmits(['select']);
const deptList = ref<any[]>([]); // 部门列表
const deptTree = ref<any[]>([]); // 部门树
const loading = ref(false); // 加载状态

// const expandedKeys = ref<number[]>([]); // 展开的节点
// const searchValue = ref(''); // 搜索值

/** 处理搜索逻辑 */
// function handleSearch(e: any) {
//   const value = e.target.value;
//   searchValue.value = value;
//   const filteredList = value
//     ? deptList.value.filter((item) =>
//       item.name.toLowerCase().includes(value.toLowerCase()),
//     )
//     : deptList.value;
//   deptTree.value = handleTree(filteredList);
//   // 展开所有节点
//   expandedKeys.value = deptTree.value.map((node) => node.id as number);
// }

/** 选中部门 */
const handleSelect = (_selectedKeys: any[], info: any) => {
  console.log('选中部门', info.node.dataRef);
  emit('select', info.node.dataRef);
};

/** 初始化 */
onMounted(async () => {
  try {
    loading.value = true;
    const data = await getDingdDeptInfoTree();
    deptList.value = data;
    deptTree.value = handleTree(data);
  } catch (error) {
    console.error('获取部门数据失败', error);
  } finally {
    loading.value = false;
  }
});
// 同步按钮
const isSyncDisabled = ref(false);
const handleSync = async () => {
  try {
    isSyncDisabled.value = true;
    await getDingdDeptInfoSync();
    const data = await getDingdDeptInfoSyncState();
    if (data) {
      const treeData = await getDingdDeptInfoTree();
      if (treeData.length > 0) {
        message.success('同步成功');
        deptList.value = treeData;
        deptTree.value = handleTree(treeData);
      }
    } else {
      message.error('同步失败');
    }
  } catch (error) {
    console.error('同步部门数据失败', error);
  } finally {
    isSyncDisabled.value = false; // 无论成功失败都启用按钮
  }
};
</script>

<template>
  <div>
    <!-- <div class="mb-2">
      <Input placeholder="搜索部门" allow-clear v-model:value="searchValue" @change="handleSearch" class="w-full">
      <template #prefix>
        <Search class="size-4" />
      </template>
</Input>
</div> -->
    <!-- <a-button style="float: right" type="primary" @click="handleSync" :disabled="isSyncDisabled">同步</a-button> -->
    <Tree
      style="margin-top: 20px"
      :spinning="loading"
      class="pt-1"
      v-if="deptTree.length > 0"
      :tree-data="deptTree"
      :field-names="{ title: 'name', key: 'id', children: 'children' }"
      @select="handleSelect"
      :default-expand-all="true"
    />
    <div v-else-if="!loading" class="py-4 text-center text-gray-500">
      暂无数据
    </div>
  </div>
</template>
